const { User } = require('../models');
const { validateEmail, validatePassword, validateUsername, validateWalletAddress } = require('../utils/validation');
const { errorResponse } = require('../utils/response');

class UserService {
    async createUser(userData) {
        if (!validateEmail(userData.email)) {
            throw new Error('Invalid email format');
        }
        if (!validatePassword(userData.password)) {
            throw new Error('Password must be at least 6 characters long');
        }
        if (!validateUsername(userData.username)) {
            throw new Error('Username must be between 3 and 20 characters');
        }
        if (userData.walletAddress && !validateWalletAddress(userData.walletAddress)) {
            throw new Error('Invalid wallet address');
        }

        return await User.create(userData);
    }

    async getUserById(userId) {
        const user = await User.findByPk(userId);
        if (!user) {
            throw new Error('User not found');
        }
        return user;
    }

    async updateUserBalance(userId, amount) {
        const user = await this.getUserById(userId);
        user.balance += parseFloat(amount);
        await user.save();
        return user;
    }

    async updateUserExperience(userId, experience) {
        const user = await this.getUserById(userId);
        user.experience += experience;
        
        // Level up logic
        while (user.experience >= 100) {
            user.level += 1;
            user.experience -= 100;
        }
        
        await user.save();
        return user;
    }

    async linkWallet(userId, walletAddress) {
        if (!validateWalletAddress(walletAddress)) {
            throw new Error('Invalid wallet address');
        }

        const user = await this.getUserById(userId);
        user.walletAddress = walletAddress;
        await user.save();
        return user;
    }
}

module.exports = new UserService();